



axios.defaults.baseURL = 'http://localhost:3000/';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    const token = localStorage.getItem("token")
    console.log(token);
    token && (config.headers.authorization = token)
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    const authorization = response.headers.authorization
    authorization && localStorage.setItem("token", authorization)
    return response;
}, function (error) {


    location.href = "/"
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
});




getUsers()





function getUsers() {
    axios.get('/api/user').then(res => {
        // console.log(res.data.status);
        if (res.data.status === 1) {
            document.querySelector("tbody").innerHTML = res.data.message.map(({ username, email, _id, password, image }) => {
                // console.log(username, email, _id, password);
                return `
            <tr>
                <td>${username}</td>
                <td>${password}</td>
                <td>${email}</td>
                <td><img src="${image}" alt=""></td>
                
                <td><button id="delete" data-id="${_id}">删除</button></td>
                <td><button id="update" data-id="${_id}">修改</button></td>
            </tr>`
            }).join('')
        }
    }).catch(err => {
        // console.log(err);
        location.href = "/"
    })
}

getUsers()

document.querySelector("tbody").addEventListener("click", (e) => {
    if (e.target.tagName === "BUTTON" && e.target.id === "delete") {
        const id = e.target.dataset.id
        axios.delete(`/api/user/${id}`).then(res => {
            console.log(res.data);
            getUsers();
        }).catch(err => {
            console.log(err);
        })
    }
    if (e.target.tagName === "BUTTON" && e.target.id === "update") {
        const id = e.target.dataset.id

        const username = document.querySelector("#username").value;
        const password = document.querySelector("#password").value;
        const email = document.querySelector("#email").value;
        axios.put(`/api/user/${id}`, { username, password, email }).then(res => {
            console.log(res.data);
            getUsers();
        }).catch(err => {
            console.log(err);
        })
    }
})

document.querySelector(".but-add").addEventListener("click", (evnet) => {
    const username = document.querySelector("#username").value;
    const password = document.querySelector("#password").value;
    const email = document.querySelector("#email").value;
    const image = document.querySelector("#file-input").dataset.image;
    console.log(image);
    axios.post(`/api/user`, { username, password, email, image }).then(res => {
        console.log(res.data);
        getUsers();
    }).catch(err => {
        console.log(err);
    })

})

document.querySelector(".but-out").addEventListener("click", (evnet) => {


    axios.get(`/api/loginOut`, { username, password, email }).then(res => {
        if (res.data.status === 1) {
            location.href = "/"
        }
    }).catch(err => {
        console.log(err);
    })

})

function uploadImage() {
    const fileInput = document.getElementById('file-input');
    const file = fileInput.files[0];

    if (!file) {
        alert('请选择图片');
        return;
    }

    const formData = new FormData();
    formData.append('file', file);          // 文件字段
    formData.append('userId', '123');
    axios.post('/api/upload', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
    })
        .then(response => {
            if (response.data.status === 1) {
                fileInput.dataset.image = response.data.image

                console.log(response.data.image);
            }

        })
        .catch(error => {
            console.error('错误:', error.response?.data || error.message);
        });
}